package com.dongdongshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.user.TbAddress;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.util.HttpClientUtil;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Eayon
 * @Date 2020/4/4 21:51
 */
@Controller
@RequestMapping("order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    private static final String USER_ADDRESS_URL = "http://localhost:8765/userservice/address/";

    private static final String CART_URL = "http://localhost:8765/cartservice/cart/";

    private static final String ORDER_URL = "http://localhost:8765/orderservice/order/";


    /**
     * 跳转订单页，获取当前用户的收货地址，以及该用户选择结算的商品在购物车中的信息
     * @param itemIds
     * @param model
     * @return
     */
    @RequestMapping("toOrderInfo")
    public String toOrderInfo(@RequestParam("itemIds")Long[] itemIds, Model model){
        //获取当前登录的用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //调用用户服务 根据用户ID获取该用户的收货地址
        Map<String,String> params = new HashMap<>();
        if(user == null){
            log.warn("用户未登录");
            throw new RuntimeException("用户未登录");
        }
        Long userId = user.getId();
        String dataResultStr = HttpClientUtil.doGet(USER_ADDRESS_URL + userId, params);
        DataResult dataResult = JSONObject.parseObject(dataResultStr, DataResult.class);
        List<TbAddress> addresses = (List<TbAddress>)dataResult.getData();
        log.info("用户地址查询成功：{}",JSONObject.toJSONString(addresses));
        model.addAttribute("addressList",addresses);

        //调用购物车服务获取该用户选中购物车这几样商品的数据，（暂时不作删除，等生成订单的时候再做删除）
        //其实返回来的还是个购物车。只不过购物车里面都是用户结算时的商品
        Map<String,String> params2 = new HashMap<>();
        String username = user.getUsername();
        params2.put("username",username);
        params2.put("itemIds",JSONObject.toJSONString(itemIds));
        String dataResultStr2 = HttpClientUtil.doGet(CART_URL + "getItemsByItemId", params2);
        DataResult dataResult2 = JSONObject.parseObject(dataResultStr2, DataResult.class);
        List<Cart> carts = (List<Cart>)dataResult2.getData();
        log.info("该用户选择的购物车商品：{}",JSONObject.toJSONString(carts));
        model.addAttribute("carts",carts);
        return "order/getOrderInfo";
    }

    /**
     * 创建订单
     * @param id
     * @param carts
     */
    @RequestMapping("addOrder")
    @ResponseBody
    public DataResult addOrder(Long id,String carts){
        try {
            //获取登录用户
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            //需要创建订单的购物车
            List<Cart> cartList = JSON.parseArray(carts, Cart.class);
            //orderService.addOrder(cartList, id, user);//返回主订单id
            //调用订单服务，创建订单
            Map<String,String> params = new HashMap<>();
            params.put("carts",JSONObject.toJSONString(cartList));
            params.put("id",id.toString());
            params.put("user",JSONObject.toJSONString(user));
            String dataResultStr = HttpClientUtil.doPost(ORDER_URL + "addOrder", params);
        }catch (Exception e){
            log.error("创建订单异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage());
    }

    /**
     * 跳转支付页面
     * @return
     */
    @RequestMapping("toPay")
    public String toPay(){
        return "order/pay";
    }
}
